<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Users extends MX_Controller {

    private $module = 'users';
    private $table = 'users';
    private $user = false;

    function __construct() {
        parent::__construct();
        $this->load->model($this->module . '_model', 'model');
        $this->load->model('admincp_modules/admincp_modules_model');
        if ($this->uri->segment(1) == 'admincp') {
            if ($this->uri->segment(2) != 'login') {
                if (!$this->session->userdata('userInfo')) {
                    header('Location: ' . PATH_URL . 'admincp/login');
                    return false;
                }
                $get_module = $this->admincp_modules_model->check_modules($this->uri->segment(2));
                $this->session->set_userdata('ID_Module', $get_module[0]->id);
                $this->session->set_userdata('Name_Module', $get_module[0]->name);
            }
            $this->template->set_template('admin');
            $this->template->write('title', 'Admin Control Panel');
        }
    }

    /* ------------------------------------ Admin Control Panel ------------------------------------ */

    public function admincp_index() {
        modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'r', 0);
        $default_func = 'created';
        $default_sort = 'DESC';
        $data = array(
            'module' => $this->module,
            'module_name' => $this->session->userdata('Name_Module'),
            'default_func' => $default_func,
            'default_sort' => $default_sort
        );
        $this->template->write_view('content', 'BACKEND/index', $data);
        $this->template->render();
    }
     public function admincp_upload_excel($id = 0) {
        $data = array(
            'module' => $this->module,
            'id' => $id
        );
        $this->template->write_view('content', 'BACKEND/ajax_upload_excel', $data);
        $this->template->render();
    }
    public function admincp_update($id = 0) {
        if ($id == 0) {
            modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 0);
        } else {
            modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'r', 0);
        }
        $result[0] = array();
        if ($id != 0) {
            $result = $this->model->getDetailManagement($id);
        }
        $data = array(
            'result' => $result[0],
            'module' => $this->module,
            'id' => $id
        );
        $this->template->write_view('content', 'BACKEND/ajax_editContent', $data);
        $this->template->render();
    }

    public function admincp_save() {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        if ($_POST) {
            //Upload Image
            $fileName = array('image' => '');
            if ($_FILES) {
                foreach ($fileName as $k => $v) {
                    if (isset($_FILES['fileAdmincp']['error'][$k])) {
                        $typeFileImage = strtolower(substr($_FILES['fileAdmincp']['type'][$k], 0, 5));
                        if ($typeFileImage == 'image') {
                            $tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
                            $file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
                            $ext = strtolower(substr($file_name[$k], -4, 4));
                            if ($ext == 'jpeg') {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -5)) . '.jpg';
                            } else {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -4)) . $ext;
                            }
                        } else {
                            print 'Only upload Image.';
                            exit;
                        }
                    }
                }
            }
            //End Upload Image

            if ($this->model->saveManagement($fileName)) {
                //Upload Image
                if ($_FILES) {
                    foreach ($fileName as $k => $v) {
                        if (isset($_FILES['fileAdmincp']['error'][$k])) {
                            $upload_path = BASEFOLDER . DIR_UPLOAD_NEWS;
                            move_uploaded_file($tmp_name[$k], $upload_path . $fileName[$k]);
                        }
                    }
                }
                //End Upload Image
                print 'success';
                exit;
            }
        }
    }

    public function admincp_delete() {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'd', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        if ($this->input->get_post('id')) {
            $id = $this->input->get_post('id');
            $result = $this->model->getDetailManagement($id);
            modules::run('admincp/saveLog', $this->module, $id, 'Delete', 'Delete');
            $this->db->where('id', $id);
            if ($this->db->delete(PREFIX . $this->table)) {
                //Xóa hình khi Delete
                @unlink(BASEFOLDER . DIR_UPLOAD_NEWS . $result[0]->image);
                return true;
            }
        }
    }

    public function admincp_ajaxLoadContent() {
        $this->load->library('AdminPagination');
        $config['total_rows'] = $this->model->getTotalsearchContent();
        $config['per_page'] = $this->input->get_post('per_page');
        $config['num_links'] = 3;
        $config['func_ajax'] = 'searchContent';
        $config['start'] = $this->input->get_post('start');
        $this->adminpagination->initialize($config);

        $result = $this->model->getsearchContent($config['per_page'], $this->input->get_post('start'));
        $data = array(
            'result' => $result,
            'per_page' => $this->input->get_post('per_page'),
            'start' => $this->input->get_post('start'),
            'module' => $this->module
        );
        $this->session->set_userdata('start', $this->input->get_post('start'));
        $this->load->view('BACKEND/ajax_loadContent', $data);
    }

    public function admincp_ajaxUpdateStatus() {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print '<script type="text/javascript">show_perm_denied()</script>';
            $status = $this->input->get_post('status');
            $data = array(
                'status' => $status
            );
        } else {
            if ($this->input->get_post('status') == 0) {
                $status = 1;
            } else {
                $status = 0;
            }
            $data = array(
                'status' => $status
            );
            modules::run('admincp/saveLog', $this->module, $this->input->get_post('id'), 'status', 'update', $this->input->get_post('status'), $status);
            $this->db->where('id', $this->input->get_post('id'));
            $this->db->update(PREFIX . $this->table, $data);
        }

        $update = array(
            'status' => $status,
            'id' => $this->input->get_post('id'),
            'module' => $this->module
        );
        $this->load->view('BACKEND/ajax_updateStatus', $update);
    }
     public function admincp_import_excel() {
        //Upload Image
        $fileName = array('excel' => '');
        if ($_FILES) {
            foreach ($fileName as $k => $v) {
                if (isset($_FILES['fileAdmincp']['error'][$k])) {
                    $typeFileImage = strtolower(substr($_FILES['fileAdmincp']['name'][$k], strrpos($_FILES['fileAdmincp']['name'][$k], '.') + 1));
                    if ($typeFileImage == 'xlsx' || $typeFileImage == 'xls') {
                        $tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
                        $file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
                        $ext = strtolower(substr($_FILES['fileAdmincp']['name'][$k], strrpos($_FILES['fileAdmincp']['name'][$k], '.') + 1));
                        if ($ext == '.xlsx') {
                            $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -5)) . '.xls';
                        } else {
                            $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -4)) . '.' . $ext;
                        }
                    } else {
                        print 'Only upload Image.';
                        exit;
                    }
                }
            }
        }
        //End Upload Image
        //Upload Image
        if ($_FILES) {
            foreach ($fileName as $k => $v) {
                if (isset($_FILES['fileAdmincp']['error'][$k])) {
                    $upload_path = BASEFOLDER . DIR_UPLOAD_EXCEL;
                    move_uploaded_file($tmp_name[$k], $upload_path . $fileName[$k]);
                    $file = BASEFOLDER . 'static/uploads/excel/' . $fileName[$k];
                }
            }
         
            ini_set("memory_limit", "100M");
            require_once 'application/libraries/PHPExcel.php';

            $objPHPExcel = new PHPExcel();

            $objReader = new PHPExcel_Reader_Excel2007();
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($file);

            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
            $array_data = array();

            foreach ($rowIterator as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
                if (1 == $row->getRowIndex())
                    continue; //skip first row
                $rowIndex = $row->getRowIndex();
                $array_data[$rowIndex] = array('A' => '', 'B' => '', 'C' => '', 'D' => '','E' => '');

                foreach ($cellIterator as $cell) {
                    if ('A' == $cell->getColumn()) {
                        //$array_data[$rowIndex][$cell->getColumn()] = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cell->getCalculatedValue()));
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }
                    if ('B' == $cell->getColumn()) {
                        //$array_data[$rowIndex][$cell->getColumn()] = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cell->getCalculatedValue()));
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }
                    if ('C' == $cell->getColumn()) {
                        //$array_data[$rowIndex][$cell->getColumn()] = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cell->getCalculatedValue()));
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }
                    if ('D' == $cell->getColumn()) {
                        //$array_data[$rowIndex][$cell->getColumn()] = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cell->getCalculatedValue()));
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }
                    if ('E' == $cell->getColumn()) {
                        //$array_data[$rowIndex][$cell->getColumn()] = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cell->getCalculatedValue()));
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }
                    
                    
                }
            }

            foreach ($array_data as $v) {
                $username = $v['A'];
                $email = $v['A'];
                $password = md5('111111');
                $fullname = $v['B'];
                $address = $v['C'];
                $phone = $v['D'];
                $cmnd = $v['E'];
                $data = array(
                'type' => 1,
                'username' => $username,
                'email' => $email,
                'password' => $password,
                'fullname' => $fullname,
                'cmnd' => $cmnd,
                'phone' => $phone,
                'address' => $address,
                'climax' => 1,
                'status' => 1,
                'created' => date('Y-m-d H:i:s')
             );
             $this->db->insert('cli_user', $data);
  
            }
            print 'success';
            exit;
        }	
    }
    /* ------------------------------------ End Admin Control Panel -------------------------------- */

    function index() {
        $action = $this->input->get_post('action');

        switch ($action) {
            case "Login":
                $this->login();
                break;
            case "Logout":
                $this->logout();
                break;
            case "Register":
                $this->register();
                break;
            case "Profile":
                $this->profile();
                break;
            case "ForgetPass":
                $this->forgotpass();
                break;
            case "Active-Forgotpass":
                $this->active_forgotpass();
                break;
            case "active-user":
                $this->active();
                break;
            case "get-bantron":
                $this->congdong();
                break;
            case "get-TT18":
                $this->thachthuc();
                break;
            case "get-bantronchitiet":
                if ($this->input->post('type') == "DaDang") {
                    $this->congdong_detail("DaDang");
                } else {
                    $this->congdong_detail("ThamGia");
                }
                break;
            default:
                $this->_refesh();
        }
    }

    function register() {

        $type = $this->input->get_post('type');
        $error = false;
        $arr_error = array();
        $this->model->validate_username($arr_error, $error);
        $this->model->validate_email($arr_error, $error);
        $this->model->validate_password($arr_error, $error);
        $this->model->validate_re_password($arr_error, $error);
        $this->model->validate_fullname($arr_error, $error);
        $this->model->validate_day($arr_error, $error);
        $this->model->validate_phone($arr_error, $error);
        $this->model->validate_cmnd($arr_error, $error);
        $this->model->validate_address($arr_error, $error);

        $json['st'] = (empty($error)) ? 'SUCCESS' : 'FALSE';
        $json['error'] = $arr_error;
        if ($error == false) {
            //SUCCESS
            $this->model->insert_user();
            $json['email'] = $this->input->get_post('email');
            if ($type != 'fb') {
                $this->_xml_session_ok('register-success');
                exit();
            }
        } else {
            if ($type != 'fb') {
                $this->_xml_session_error('register-error');
                exit();
            }
        }
        return print_r(json_encode($json));
    }

    function login() {
        $type = $this->input->get_post('type');
        $error = false;
        $arr_error = array();
        $this->model->validate_email($arr_error, $error, true);
        $this->model->validate_password($arr_error, $error, true);

        $email = mysql_real_escape_string($this->input->get_post('email'));
        $password = md5($this->input->get_post('password'));
        $type = $this->input->get_post('type');
        $USER = $this->model->get('*', USER_TB, "`email` = '$email' AND `password` = '$password' AND status = 1");

        if (!empty($USER)) {
            //SUCCESS
            $this->session->set_userdata('ss_user_id', $USER->id);
            $this->session->set_userdata('ss_user_email', $USER->email);
            $this->session->set_userdata('ss_user_fullname', $USER->fullname);
            $this->model->history_ip($USER);
            if ($this->input->get_post('remember') == 'checked') {
                //REMEMBER
                $cookie = _token();
                setcookie("__email", $USER->email, time() + 604800, '/');  /* expire in 7 day */
                setcookie("__password", $cookie, time() + 604800, '/');  /* expire in 7 day */

                $data_user['cookie'] = $cookie;
                $this->db->where('id', $USER->id)->update(USER_TB, $data_user);
            } else {
                setcookie("__email", '', time() - 604800, '/');
                setcookie("__password", '', time() - 604800, '/');
            }
            $this->user = $USER;

            $json = array(
                'st' => 'SUCCESS',
                'txt' => 'Đăng nhập thành công'
            );
            if ($type != 'fb') {
                $this->_xml_session_ok('login-success', 'Đăng nhập thành công');
                exit();
            }
        } else {
            //FALSE
            $json = array(
                'st' => 'FALSE',
                'txt' => 'Tên đăng nhập hoặc mật khẩu không đúng'
            );
            if ($type != 'fb') {
                $this->model->_xml_session_error('login-fail', 'Email hoặc mật khẩu không đúng');
                exit();
            }
        }
        print_r(json_encode($json));
    }

    function link_login($type = 'google') {
        echo url_login_openid($type);
    }

    function getProfile_google($access_token) {
        $_GET['access_token'] = $access_token;
        $info = get_attr_profile_openid('google');
        if (!empty($info['email'])) {
            $USER = $this->model->get('*', USER_TB, "`email` = '" . $info['email'] . "'");
            $username = explode('@', $info['email']);
            if (empty($USER)) {
                $data = array(
                    'type' => 3,
                    'username' => $username[0],
                    'email' => $info['email'],
                    'fullname' => $info['full_name'],
                    'randomkey' => _token(),
                    'created' => date('Y-m-d H:i:s')
                );
                $this->db->insert(USER_TB, $data);
            } else {
                //$this->db->where('id', $USER->id)->update(USER_TB, $data);
            }
            $USER = $this->model->get('*', USER_TB, "`email` = '" . $info['email'] . "'");
            $this->user = $USER;
            $this->model->history_ip($USER);
            $this->session->set_userdata('ss_user_id', $USER->id);
            echo 'SUCCESS';
        }
        //pr(get_attr_profile_openid('google'), 1);
    }

    function getProfile_yahoo() {
        //pr(get_attr_profile_openid('yahoo'), 1);
        $info = get_attr_profile_openid('yahoo');
        if (!empty($info['email'])) {
            $USER = $this->model->get('*', USER_TB, "`email` = '" . $info['email'] . "'");
            $username = explode('@', $info['email']);
            if (empty($USER)) {
                $data = array(
                    'type' => 4,
                    'username' => $username[0],
                    'email' => $info['email'],
                    'fullname' => $info['full_name'],
                    'randomkey' => _token(),
                    'created' => date('Y-m-d H:i:s')
                );
                $this->db->insert(USER_TB, $data);
            } else {
                //$this->db->where('id', $USER->id)->update(USER_TB, $data);
            }
            $USER = $this->model->get('*', USER_TB, "`email` = '" . $info['email'] . "'");
            $this->user = $USER;
            $this->model->history_ip($USER);
            $this->session->set_userdata('ss_user_id', $USER->id);
            echo 'SUCCESS';
        }
    }

    function OpenId($type = '') {
        $data['type'] = $type;
        $this->load->view('FRONTEND/OpenId', $data);
    }

    function LoginOpenId($type = 'google') {

        if (empty($_GET))
            exit();
        $info = get_attr_profile_openid($type);
        if (!empty($info['email'])) {
            $username = explode('@', $info['email']);
            //LOGIN SUCCESS			
            $USER = $this->model->get('*', USER_TB, "`fb_id` = '" . $info['id'] . "'");
            $this->session->set_userdata('FB', $info);
            if (empty($USER)) {
                $data = array(
                    'type' => 2,
                    'fb_id' => $info['id'],
                    'username' => $username[0],
                    'email' => $info['email'],
                    'fullname' => $info['full_name'],
                    'randomkey' => _token(),
                    'created' => date('Y-m-d H:i:s')
                );
                $this->db->insert(USER_TB, $data);
            } else {
                $data['fb_id'] = $info['id'];
                $this->db->where('id', $USER->id)->update(USER_TB, $data);
            }
            $USER = $this->model->get('*', USER_TB, "`fb_id` = '" . $info['id'] . "'");
            $this->user = $USER;
            $this->model->history_ip($USER);
            $this->session->set_userdata('ss_user_id', $USER->id);
            $this->session->set_userdata('ss_fb_id', $info['id']);
            $json['st'] = 'SUCCESS';
            $json['information'] = (empty($USER->cmnd)) ? 'FALSE' : 'TRUE';
            print_r(json_encode($json));
        }
    }

    function logout() {
        $device = $this->input->post('device');
        $this->session->unset_userdata('ss_user_id');
        $this->session->unset_userdata('ss_user_name');
        $this->session->unset_userdata('ss_user_fullname');
        $this->session->unset_userdata('ss_user_token');
        setcookie("__username", '', time() - 604800, '/');
        setcookie("__password", '', time() - 604800, '/');
        $st = 'SUCCESS';
        $register = ($this->input->post('type') == 'iphone') ? 'register_iphone' : 'register';
        $data = array(
            'register' => $register
        );
        $html = $this->load->view('FRONTEND/logout', $data, true);

        $json = array(
            'st' => 'SUCCESS',
            'html' => $html
        );
        if ($device) {
            print_r(json_encode($json));
        } else {
            $this->_xml_session_error('logout');
        }
    }

    function _xml_session_error($status) {
        header_xml();
        echo '<param method="clearSession" name="id" />';
        echo '<param method="clearSession" name="username" />';
        echo '<param method="clearSession" name="email" />';
        echo '<param method="clearSession" name="action" />';
        echo '<param method="clearSession" name="password" />';
        echo '<param method="clearSession" name="name" />';
        echo '<param method="clearSession" name="fullname" />';
        echo '<param method="clearSession" name="cmnd" />';
        echo '<param method="clearSession" name="phone" />';
        echo '<param method="clearSession" name="address" />';
        echo '<param method="clearSession" name="birthday" />';

        echo '<param method="setSession" name="login" type="Boolean">false</param>';
        echo '<param method="setSession" name="status" type="String">' . $status . '</param>';
        $this->model->_xml_session_default();
        footer_xml();
    }

    function _xml_session_ok($status = '', $message = '') {
        header_xml();
        echo '<param method="clearSession" name="action" />';
        echo '<param method="clearSession" name="password" />';
        if ($this->_me()) {
            echo '<param method="setSession" name="login" type="Boolean">true</param>';
        } else {
            echo '<param method="setSession" name="login" type="Boolean">false</param>';
        }
        echo '<param method="setSession" name="status" type="String">' . $status . '</param>';
        echo '<param method="setSession" name="error-message" type="String">' . $message . '</param>';
        if ($this->_me()) {
            echo '<param method="setSession" name="id" type="String">' . $this->user->id . '</param>';
            echo '<param method="setSession" name="email" type="String">' . $this->user->email . '</param>';
            echo '<param method="setSession" name="username" type="String">' . $this->user->username . '</param>';
            echo '<param method="setSession" name="fullname" type="String">' . $this->user->fullname . '</param>';
            echo '<param method="setSession" name="cmnd" type="String">' . $this->user->cmnd . '</param>';
            echo '<param method="setSession" name="phone" type="String">' . $this->user->phone . '</param>';
            echo '<param method="setSession" name="address" type="String">' . $this->user->address . '</param>';
            echo '<param method="setSession" name="birthday" type="String">' . date('d/m/Y', strtotime($this->user->birthday)) . '</param>';
            echo '<param method="setSession" name="linkNews" type="String">' . PATH_URL . "news/detail_news" . '</param>';
        }
        $this->model->_xml_session_default();
        footer_xml();
    }

    function usertoken() {
        $user = array();
        if ($this->user) {
            $user['id'] = $this->user->id;
            $user['username'] = $this->user->username;
            $user['fullname'] = $this->user->fullname;
            $user['email'] = $this->user->email;
            $user['phone'] = $this->user->phone;
            $user['cmnd'] = $this->user->cmnd;
        }
        $data = json_encode($user);
        $data_hash = hash_hmac('sha256', $data, 'sALRWPsN');
        $data_encode1 = base64_encode($data_hash . ';' . $data);
        $data_encode2 = str_replace('E', 'E1', $data_encode1);
        return strtr($data_encode2, array('+' => 'Ex', '/' => 'Ei', '=' => 'EE'));
    }

    function _me() {
        if (!$this->user) {
            $id = $this->session->userdata('ss_user_id');
            if ($id) {
                $user = $this->model->get('*', USER_TB, "`status` = 1 AND id = '$id'");
                if ($user && $user->id) {
                    $this->user = $user;
                }
            }
        }
        return $this->user;
    }

    function _refesh() {
        if ($this->_me()) {
            $this->_xml_session_ok('login-success');
            return;
        }
        $this->_xml_session_error('unknown');
    }

    function profile() {
        $type = $this->input->get_post('type');

        if ($this->session->userdata('ss_user_id')) {
            $USER = $this->model->get('*', USER_TB, "id = '{$this->session->userdata('ss_user_id')}'");
            $error = false;
            $arr_error = array();
            if (!empty($USER->cmnd)) {
                if ($this->input->get_post('password') != '') {
                    $this->model->validate_password($arr_error, $error);
                    $this->model->validate_re_password($arr_error, $error);
                }
            } else {
                if ($this->input->get_post('password') != '') {
                    $this->model->validate_password($arr_error, $error);
                    $this->model->validate_re_password($arr_error, $error);
                }
            }

            $this->model->validate_fullname($arr_error, $error);
            $this->model->validate_phone($arr_error, $error);
            $this->model->validate_cmnd($arr_error, $error);
            $this->model->validate_address($arr_error, $error);
            $this->model->validate_day($arr_error, $error);
            $json['st'] = (empty($error)) ? 'SUCCESS' : 'FALSE';
            $json['error'] = $arr_error;
            if ($error == false) {
                //SUCCESS
                $this->model->update_user($this->session->userdata('ss_user_id'));
                if ($type != 'fb') {
                    $this->_xml_session_ok('profile-success', 'Thay đổi thông tin thành công');
                    exit();
                }
            } else {
                if ($type != 'fb') {
                    $this->model->_xml_session_error($arr_error[0]['field'], $arr_error[0]['txt']);
                    exit();
                }
            }
            return print_r(json_encode($json));
        }
    }

    function forgotpass() {
        $email = mysql_real_escape_string($this->input->post('email'));
        $st = 'FALSE';
        $type = mysql_real_escape_string($this->input->post('type'));
        $error = false;
        $arr_error = array();
        $this->model->validate_email($arr_error, $error, true);
        //CHECK USER
        $USER = $this->model->get('*', USER_TB, "`email` = '$email'");
        if (!empty($USER)) {
            $randomkey = md5(uniqid(mt_rand())) . md5(time());
            $data['randomkey'] = $randomkey;
            $this->db->where("id", $USER->id);
            if ($this->db->update(USER_TB, $data)) {
                //SEND EMAIL
                //$link_active= PATH_URL.'user/active_forgotpass?e='.$USER->email.'&rd='.$randomkey;
                $link_active = LINK_SHARE . '#/Account/ActiveForgetPassword/' . $USER->email . '/' . $randomkey;
                $data_html = array(
                    'email' => $USER->email,
                    'link_active' => $link_active
                );
                $data_email = array(
                    'email' => $USER->email,
                    'html' => $this->load->view('FRONTEND/email/active_forgotpass', $data_html, true),
                    'subject' => 'Quên mật khẩu'
                );

                if ($this->model->send_email($data_email)) {
                    if ($type != 'fb') {
                        $this->model->_xml_session_error('forget-success', 'Bạn hãy vào email để xác nhận khôi phục mật khẩu');
                        exit();
                    }
                    $st = 'SEND';
                } else {
                    if ($type != 'fb') {
                        $this->model->_xml_session_error('forget-error', 'Khôi phục mật khẩu thất bại');
                        exit();
                    }
                    $st = 'NOT_SEND';
                }
            }
        } else {
            if ($type != 'fb') {
                $this->model->_xml_session_error('email-error', 'Địa chỉ email không tồn tại');
                exit();
            }
        }
        $json = array(
            'st' => $st
        );
        print_r(json_encode($json));
    }

    function active_forgotpass() {
        $email = mysql_real_escape_string($this->input->post('e'));
        $randomkey = mysql_real_escape_string($this->input->post('rd'));
        $USER = $this->model->get('*', USER_TB, "`email` = '$email' AND `randomkey` = '$randomkey'");
        if (!empty($USER)) {
            //SEND NEW PASS
            $password = strtoupper(random_string(10));
            $data = array(
                'password' => md5($password),
                'randomkey' => md5(uniqid(mt_rand())) . md5(time())
            );
            $this->db->where("id", $USER->id);
            if ($this->db->update(USER_TB, $data)) {
                $data_html = array(
                    'email' => $USER->email,
                    'password' => $password
                );
                //SEND EMAIL NEW PASS
                $data_email = array(
                    'email' => $USER->email,
                    'html' => $this->load->view('FRONTEND/email/forgotpass', $data_html, true),
                    'subject' => 'Mật khẩu mới'
                );
                if ($this->model->send_email($data_email)) {
                    $this->model->_xml_session_error('active-forget', 'Bạn hãy vào email để nhận lại mật khẩu');
                    exit();
                } else {
                    $this->model->_xml_session_error('active-forget', 'Không thể gửi email ngay lúc này, bạn vui lòng thử lại');
                    exit();
                }
            }
        } else {
            $this->model->_xml_session_error('active-forget', 'Link kích hoạt không hợp lệ');
            exit();
        }
    }

    public function thachthuc() {
        $ss_user_id = $this->session->userdata('ss_user_id');
        $data = array();
        $list_week = $this->model->list_week();
        header_xml();
        echo "<quiz>";
        foreach ($list_week AS $lw) {
            $list_thachthuc = $this->model->list_thachthuc($lw->id, $ss_user_id);
            echo "<item>";
            echo "<tuan>" . $lw->name . "</tuan>";
            if (empty($list_thachthuc)) {
                echo "<note><![CDATA[Không tham gia]]>.</note>";
            } else {
                if ($list_thachthuc[0]->winner == 1) {
                    echo "<note><![CDATA[Bạn đã trả lời chính xác và may mắn trúng giải]]></note>";
                } else {
                    echo "<note><![CDATA[Bạn đã trả lời sai]]></note>";
                }
            }
            echo "</item>";
        }
        echo "</quiz>";
        footer_xml();
    }

    public function congdong() {
        $ss_user_id = $this->session->userdata('ss_user_id');

        $data = array();
        $list_congdong = $this->model->list_congdong($ss_user_id, 1);
        $list_thamgia = $this->model->list_thamgia($ss_user_id, 1);
        $count_thamgia = $this->model->count_thamgia($ss_user_id, 1);
        $count_congdong = $this->model->count_congdong($ss_user_id, 1);
        header_xml();
        echo "<DaDang count='" . $count_congdong . "'>";
        if (!empty($list_congdong)) {
            foreach ($list_congdong AS $lw) {
                echo "<item>";
                echo "<tuan>" . $lw->id . "</tuan>";
                echo '<title><![CDATA[' . $lw->title . ']]></title>';
                echo "</item>";
            }
        }
        echo "</DaDang>";
        echo "<ThamGia count='" . $count_thamgia . "'>";
        if (!empty($list_thamgia)) {
            foreach ($list_thamgia AS $lt) {
                echo "<item>";
                echo "<tuan>" . $lt->id . "</tuan>";
                echo '<title><![CDATA[' . $lt->comment . ']]></title>';
                echo "</item>";
            }
        }
        echo "</ThamGia>";
        footer_xml();
    }
    function active() {
        
        $uid = mysql_real_escape_string($this->input->post('uid'));
        $code = mysql_real_escape_string($this->input->post('code'));
        $id = base64_decode($uid);
        $USER = $this->model->get('*', USER_TB, "`id` = '$id' AND `code` = '$code'");
        if (!empty($USER)) {
            
            $data = array(
                'active' => 1
            );
            $this->db->where("id", $USER->id);
            if ($this->db->update(USER_TB, $data)) {
               
                    $this->model->_xml_session_error('true', 'Bạn đã kích hoạt tài khoản thành công ');
                    exit();
                
            }
        } else {
            $this->model->_xml_session_error('false', 'Link kích hoạt không hợp lệ');
            exit();
        }
        
        
        
      
       
    }
    public function congdong_detail($type = 'DaDang') {
        $ss_user_id = $this->session->userdata('ss_user_id');

        $result = $this->model->congdong_detail($ss_user_id, $type);

        header_xml();
        if (!empty($result)) {
            foreach ($result AS $r) {

                echo "<item>";
                echo "<id>" . $r->id . "</id>";
                if ($type == "DaDang") {
                    echo "<title>" . $r->title . "</title>";
                } else {
                    echo "<title>" . $r->comment . "</title>";
                }
                echo "</item>";
                // echo "<id>".$r->id."</id>";
                // echo "<title><![CDATA[".$r->title."]]></title>";
                // echo "<content><![CDATA[".$r->content."]]></content>";
                // echo "<user><![CDATA[".$r->username."]]></user>";
                // echo "<date>".date('d/m/Y',strtotime($r->username))."</date>";
                // echo "<thumb>".date('d/m/Y',strtotime($r->username))."</thumb>";
                // echo "<link>".date('d/m/Y',strtotime($r->username))."</link>";
                // echo "<comment><![CDATA[".$r->total_comment."]]></comment>";
                // if(!empty($comment))
                // {
                // foreach($comment AS $c)
                // {
                // echo "<item>";
                // echo "<user>".$c->username."</user>";
                // echo "<created>".date('d/m/Y',strtotime($r->username))."</created>";
                // echo "<comment><![CDATA[".$r->comment."]]></comment>";
                // echo "<item>";
                // }
                // }
            }
        }
        footer_xml();
    }

    /* ------------------------------------ End FRONTEND -------------------------------- */
}